var express = require('express');
var router = express.Router();
const shsDB = require("./../../db/index.js");

router.post("/set",jwtVerify, function(req, res) {
	let obj = {
		code: 201,
		message: "",
		data: {
			message: "", //业务消息
		}
	}
	try {
		let item = req.body;
		if (!item.code || item.code == undefined || item.value == undefined) {
			obj.message = "参数不合法"
			res.send(JSON.stringify(obj))
			return
		}
		let authoritySql =
			`select isAdmin from users where Id=${req.shsImUserInfo.fromId} and status=1;`
		shsDB(authoritySql).then(data => {
			if (data && data[0].isAdmin == 1) {
				let params = [item.value]
				let sql = `INSERT INTO \`imdb\`.\`dict\`(\`id\`, \`code\`, \`value\`,\`notes\`, \`status\`, \`createTime\`, \`updateTime\`) 
				VALUES (null, '${item.code}', ?,'${item.notes}', '1', '${getdate()}','${getdate()}');`
				return shsDB(sql, params)
			}
			obj.message = "您没有权限访问!!!"
			throw new Error("not authority");
		}).then(data => {
			obj.code = 200
			obj.data = data
			res.send(JSON.stringify(obj))
		}).catch(err => {
			obj.message = err.message;
			res.send(JSON.stringify(obj))
		})
	} catch (e) {
		obj.message = e.message;
		res.send(JSON.stringify(obj))
	}

})
router.post("/update",jwtVerify, function(req, res) {
	let obj = {
		code: 201,
		message: "",
		data: {
			message: "", //业务消息
		}
	}
	try {
		let item = req.body;
		if (!item.code || item.code == undefined || item.value == undefined) {
			obj.message = "参数不合法"
			res.send(JSON.stringify(obj))
			return
		}
		let authoritySql =
			`select isAdmin from users where Id=${req.shsImUserInfo.fromId} and status=1;`
		shsDB(authoritySql).then(data => {
			if (data && data[0].isAdmin == 1) {
				let params = [item.value]
				let sql = `update dict set dict.value=? where dict.code='${item.code}'`
				return shsDB(sql, params)
			}
			obj.message = "您没有权限访问!!!"
			throw new Error("not authority");
		}).then(data => {
			obj.code = 200
			obj.data = data
			res.send(JSON.stringify(obj))
		}).catch(err => {
			obj.message = err.message;
			res.send(JSON.stringify(obj))
		})
	} catch (e) {
		obj.message = e.message;
		res.send(JSON.stringify(obj))
	}

})
/**id
code
value
notes
status
createTime
updateTime
*/
router.post("/get", function(req, res) {
	let obj = {
		code: 201,
		message: "",
		data: {
			message: "", //业务消息
		}
	}
	try {
		let item = req.body;
		if (!item.code) {
			obj.message = "参数不合法"
			res.send(JSON.stringify(obj))
			return
		}
		let sql = `select * from dict where code='${item.code}'`;

		shsDB(sql).then(data => {
			obj.code = 200
			obj.data = data
			res.send(JSON.stringify(obj))
		}).catch(err => {
			obj.message = err.message;
			res.send(JSON.stringify(obj))
		})
	} catch (e) {}

})
//ai
//查询
router.post("/getWithPagination", async function (req, res) {
    let obj = {
        code: 201,
        message: "",
        data: {
            list: [], // 存放查询结果的数组
            total: 0, // 总记录数
            page: 1, // 当前页码
            pageSize: 10 // 每页显示的记录数
        }
    };
    try {
        let item = req.body;
        if (!item.page || !item.pageSize) {
            obj.message = "分页参数不合法";
            res.send(JSON.stringify(obj));
            return;
        }

        // 构造分页查询的SQL语句
        let sql = `SELECT * FROM dict where code!='sensitiveWords' and code!='pageSlefDetail' ORDER BY createTime DESC LIMIT ${(item.page - 1) * item.pageSize}, ${item.pageSize}`;
        let totalSql = `SELECT COUNT(*) AS total FROM dict  where code!='sensitiveWords'  and code!='pageSlefDetail' `;

        // 查询当前页的数据
        let data = await shsDB(sql);
        // 查询总记录数
        let totalData = await shsDB(totalSql);

        obj.code = 200;
        obj.data.list = data;
        obj.data.total = totalData[0].total;
        obj.data.page = item.page;
        obj.data.pageSize = item.pageSize;

        res.send(JSON.stringify(obj));
    } catch (err) {
        obj.message = err.message;
        res.send(JSON.stringify(obj));
    }
});
//新增字典
router.post("/addDict", async function (req, res) {
    let obj = {
        code: 201,
        message: "",
        data: {}
    };

    try {
        let item = req.body;
        if (!item.code || !item.value || !item.notes) {
            obj.message = "参数不完整";
            res.send(JSON.stringify(obj));
            return;
        }

        // 检查code是否已存在
        let checkSql = `SELECT COUNT(*) AS count FROM dict WHERE code='${item.code}'`;
        let checkResult = await shsDB(checkSql);

        if (checkResult[0].count > 0) {
            obj.message = "字典代码已存在";
            res.send(JSON.stringify(obj));
            return;
        }

        // 新增字典
        let insertSql = `INSERT INTO dict (code, value, notes, status, createTime, updateTime) VALUES ('${item.code}', '${item.value}', '${item.notes}', 1, NOW(), NOW())`;
        await shsDB(insertSql);

        obj.code = 200;
        obj.message = "新增成功";
        res.send(JSON.stringify(obj));
    } catch (err) {
        obj.message = err.message;
        res.send(JSON.stringify(obj));
    }
});
// 修改字典接口
router.post('/updateDict', async (req, res) => {
  let obj = {
    code: 201,
    message: '',
    data: {}
  };

  try {
    const { id, code, value, notes, status } = req.body;

    // 参数校验
    if (!id || !code || !value || !notes || status === undefined) {
      obj.message = '参数不完整';
      res.send(JSON.stringify(obj));
      return;
    }

    // 检查code是否已存在（排除当前记录）
    const checkSql = `SELECT COUNT(*) AS count FROM dict WHERE code='${code}' AND id<>${id}`;
    const checkResult = await shsDB(checkSql);

    if (checkResult[0].count > 0) {
      obj.message = '字典代码已存在';
      res.send(JSON.stringify(obj));
      return;
    }

    // 更新字典
    const updateSql = `
      UPDATE dict 
      SET code='${code}', value='${value}', notes='${notes}', status=${status}, updateTime=NOW() 
      WHERE id=${id}
    `;
    await shsDB(updateSql);

    obj.code = 200;
    obj.message = '修改成功';
    res.send(JSON.stringify(obj));
  } catch (err) {
    obj.message = err.message || '修改失败';
    res.send(JSON.stringify(obj));
  }
});

module.exports = router;